package it.unibo.deis.lia.mmhc.spm;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.BindException;
import java.net.Socket;
import java.net.SocketException;

public class ServiceClientThread extends Thread{
	
	

	private Socket input=null;
	private ServiceClient client=null;
	protected SocketVector socketVector=null;
	
	public ServiceClientThread(Socket socket, ServiceClient client) {
		super();
		this.input = socket;
		this.client=client;
		this.socketVector=SocketVector.getInstance();
	}
	
	public void run(){
		try{
			do{try{
			System.err.println("Postaccept");
		ObjectInputStream ois = new ObjectInputStream(input
				.getInputStream());
		
		// System.err.println("\tRicevuto oggetto da " + remoteSenderIP
		// + " alle " + System.currentTimeMillis());
		
			
		
		System.err.println("preread");
		Object obj=null;
		if(!input.isClosed())
		obj = ois.readObject();
		
		
		System.err.println("postread");

		ServicePathServer.addLocalService(client.getName2(), client.getPort(), input);

		System.err.println("post add");
		ServicePacket packet = new ServicePacket(client.getName2(), client.getPort(), client.getFornitore(),
				client.getRichiedente(), client.getGoHop(), client.getBackHop(), obj);
		
		
		String hop = packet.nextHop();
		Socket out = null;
		
				out = socketVector.getSoket(hop, 2500);
		if(out==null)
				System.err.println("Nuova socket creata");
		ObjectOutputStream oos = new ObjectOutputStream(out
				.getOutputStream());
		oos.flush();
		oos.writeObject(packet);
		System.err.println("Inviata");
		oos.flush();
		}catch (SocketException e) {
			System.err.println("Socket chiusa");
			//break;
		}
		}while(!input.isClosed());
		}
	
		catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		}
	}


